<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import TEditor from '@/components/tinymce/TEditor.vue'
import { useRoute, useRouter } from 'vue-router'
import { getAttrListByCategoryId } from '@/api/attr'
import CunstomerUpload from '@/components/upload/CunstomerUpload.vue'
import type { InputInstance } from 'element-plus'
import { saveSpu } from '@/api/product'
import { useProductStore } from '@/stores/modudels/product2'

const router = useRouter()
const $route = useRoute()
const productStore = useProductStore()

//表单数据
let formData = productStore.formData

//获取route中的分类id
const getPathCatId = () => {
  return $route.query.catid
}
//属性及属性值
const attrRes = ref()
const allAttrAndValues = computed(() => {
  let arr:any = []
  if (attrRes.value) {
    attrRes.value.forEach((item) => {
      arr = arr.concat(item.attrValueDTOList)
    })
  }
  return arr
})

//onMounted生命周期函数
onMounted(async () => {
  //获取分类id
  const catId = getPathCatId()
  //获取分类下的属性及属性值
  const result = await getAttrListByCategoryId(catId)
  if (result.code === 200) {
    attrRes.value = result.data
  }
})
//多选框: 选择的值
const checkedAttrValues = ref([])
//多选框: 值改变的方法
const valuesChange = () => {
  //值改变则重新生成sku列表
  let attrValueComb = generatSkuList(checkedAttrValues)
  console.log('attrValueComb', attrValueComb)
  //重置skuTableData.value=[]
  skuTableData.value=[]
  attrValueComb?.map((item) => {
    let skuName = ''
    let attrValueIds = []
    if (item.length > 1) {
      item.forEach((item2) => {
        skuName = skuName + item2.name
        attrValueIds.push(item2.id)
      })
    }
    else {
      skuName = item.name
      attrValueIds.push(item.id)
    }
    skuTableData.value.push({
      skuAttrName: skuName,
      price: 0,
      countPrice: 0,
      cukun: 0,
      yujing: 0,
      skuNum: 0,
      attrValueIds
    })

  })
}
//sku表格数据
const skuTableData  = ref([])
//生成sku列表
const generatSkuList = (checkedAttrValues:number[]) => {
  //根据选择的值从allAttrAndValues中过滤出对应的属性值
  return cartesianProduct()
}
//生成sku列表 : 1.从所有属性值中过滤出选中的属性值
const filterAttrValues = ()=>{
 return  allAttrAndValues.value.filter((item) => {
    return checkedAttrValues.value.includes(item.id)
  })
}
//生成sku列表 : 2.将属性值按照attrId进行分组
const groupedAttrValues = ()=>{
  let filterAttrValue = filterAttrValues()
  //将过滤后的属性值按照attrId进行分组
  return  filterAttrValue.reduce((acc, cur) => {
    if (!acc[cur.attrId]) {
      acc[cur.attrId] = []
    }
    acc[cur.attrId].push(cur)
    return acc
  }, [])
}
////生成sku列表 : 3.将分组后的属性值进行笛卡尔积
const cartesianProduct = ()=>{
  let groupedAttrValue = groupedAttrValues()
  return  cartesian(groupedAttrValue)
}
//笛卡尔积
const cartesian = (arr) =>{
  if (arr.length === 0) {
    return
  }else {
    return arr.reduce((acc, cur) =>
      acc.flatMap(x=> cur.map(y=>[x,y].flat()))
    )
  }
}

//子组件上传图片后, 父组件更新数据
const updateSkuImg = (index, url) =>{
  console.log(index)
  console.log(url)
  console.log(skuTableData.value)
  skuTableData.value[index].imgUrl = url
}

const spuDetailRef = ref(null)
//提交表单
const handleSubmit =async () => {
  formData.categoryId = getPathCatId()
  formData.spuContent = spuDetailRef.value.handleGetContent()
  formData.skuInfoList = skuTableData.value
  const result = await saveSpu(formData)
  if (result.code == 200) {
    router.push('/product/spu').then(() => {
      //清空formData
      productStore.clearFormData()
    })

  }
}


const getEditorContent = (event)=>{
  console.log(spuDetailRef.value.handleGetContent())
  //阻止默认行为
  event.preventDefault()
}
</script>

<template>
  <div class="add_spu_layout">
    <el-form label-width="auto" label-position="left">
      <el-form-item>
        <span>商品基本信息</span>
      </el-form-item>
      <!--商品标题-->
      <el-form-item label="商品标题">
        <el-input v-model="formData.title" placeholder="请输入商品标题" />
      </el-form-item>
      <!--      商品副标题-->
      <el-form-item label="商品副标题" class="desc_text_area_layout">
        <el-input
          v-model="formData.subTitle"
          class="text_area_class"
          placeholder="请输入商品副标题"
        />
      </el-form-item>
      <!--      商品介绍-->
      <el-form-item label="商品介绍" class="desc_text_area_layout">
        <el-input
          v-model="formData.description"
          class="text_area_class" type="textarea"
                  placeholder="请输入商品介绍"></el-input>
      </el-form-item>

      <el-form-item>
        <span>商品促销信息</span>
      </el-form-item>
      <el-form-item label="赠送积分">
        <el-input
        v-model="formData.credits"
        ></el-input>
      </el-form-item>
      <el-form-item label="预告商品">
        <el-switch
        v-model="formData.isPreview"
        ></el-switch>
      </el-form-item>
      <el-form-item label="商品推荐">
        <el-switch
          v-model="formData.isRecommend"
          inline-prompt active-text="推荐" inactive-text="不设置为推荐"
        ></el-switch>
        <el-switch
          v-model="formData.isNew"
          inline-prompt active-text="新品" inactive-text="不设置为新品"></el-switch>
      </el-form-item>
      <!--      <el-form-item v-if="attrListRes.length>0">-->
      <el-form-item>
        <span>商品属性</span>
        <!--        选择规格属性-->
        <el-card>
          <div v-for="(item) in attrRes" :key="item">
            {{ item.name }}:
            {{ item.id }}

            <el-checkbox-group
              v-model="checkedAttrValues"
              @change="valuesChange">
              <el-checkbox
                :label="attrValue.name"
                :value="attrValue.id"
                v-for="attrValue in item.attrValueDTOList"
                :key="attrValue"
              />
            </el-checkbox-group>
          </div>
        </el-card>
      </el-form-item>

      <el-form-item>
        <el-table :data="skuTableData" fit border>
          <el-table-column label="sku组合" width="100px">
            <template #default="scope">
              <span>{{ scope.row.skuAttrName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="销售价格" width="100px">
            <template #default="scope">
              <el-input v-model="scope.row.price"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="促销价格" width="100px">
            <template #default="scope">
              <el-input v-model="scope.row.countPrice"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="库存" width="80px">
            <template #default="scope">
              <el-input v-model="scope.row.cukun"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="库存预警值" width="100px">
            <template #default="scope">
              <el-input v-model="scope.row.yujing"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="sku编号" width="180px">
            <template #default="scope">
              <el-input v-model="scope.row.skuNum"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="sku主图" width="auto">
            <template #default="scope">
              <CunstomerUpload @updateImgUrls="updateSkuImg" :index="scope.$index" :imgUrls="scope.row.imgUrl"></CunstomerUpload>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item label="商品详情">
        <template #default>
          <button @click="getEditorContent">获取富文本内容</button>
          <TEditor ref="spuDetailRef"></TEditor>
        </template>
      </el-form-item>

      <!--      提交表单-->
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </el-form-item>

    </el-form>
  </div>

</template>

<style scoped lang="scss">

</style>
